package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.Code;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessPoolDTO;
import com.qk.dto.business.BusinessQueryDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Transactional
    @Override
    public void convertToCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.TRANSFORM_TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setBusinessId(business.getId() );
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        this.customerMapper.insert(customer);

    }

    @Override
    public PageResult<BusinessDO> selectBusinessPoolPage(BusinessPoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<BusinessDO> list = this.baseMapper.selectBusinessPoolPage(dto);
        return PageResult.<BusinessDO>builder()
                .total(list.getTotal())
                .rows(list.getResult())
                .build();
    }

    @Transactional
    @Override
    public void back(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECOVERY);
        this.baseMapper.updateById(business);
    }

    @Transactional
    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if (business.getStatus()== BusinessStatusConstants.WAIT_FOLLOW_UP){
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(businessTrackRecord);

    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        // 查询商机信息
        Business business = this.getById(id);
        //
        Integer userId = business.getUserId();
        User user = userMapper.getUserById(userId);
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id));

        //封装BusinessVO
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        //封装BusinessTrackRecordVO 到BusinessVO.BusinessTrackRecordVO 转换流
        List<BusinessVO.BusinessTrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item, BusinessVO.BusinessTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.save(business);

    }
    @Override
    public PageResult<BusinessDO> selectPage(BusinessQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<BusinessDO> list = this.baseMapper.selectByPage(dto);
        return PageResult.<BusinessDO>builder()
                .total(list.getTotal())
                .rows(list.getResult())
                .build();
    }


}
